﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Beyondsoft.Tuanju.DataManager;
using Windows.Networking.Connectivity;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace Tuan
{
    public sealed partial class MainPage : Tuan.Common.LayoutAwarePage
    {
        /// <summary>
        /// Initialize main page 
        /// </summary>
        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Binding context data when navigating this page
        /// </summary>
        /// <param name="e">Navigation event arguments</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            this.GrayPanel.Visibility = Visibility.Visible;
            bool networkStatus = VerifyNetworkConnectionStatus();
            if (!networkStatus)
            {
                MessageDialog ConDlg = new MessageDialog("网络连接失败，请检查网络连接。");
                await ConDlg.ShowAsync();
                App.Current.Exit();
                return;
            }
            else
            {
                this.GrayPanel.Visibility = Visibility.Visible;
                this.LoadingPanel.Visibility = Visibility.Visible;
                
                await Settings.Initialize();

                if (Settings.Providers.Count == 0) 
                {
                    MessageDialog providerNullDialog = new MessageDialog("当前没有可用的团购服务，请稍候再试！");
                    await providerNullDialog.ShowAsync();
                    App.Current.Exit();
                    return;
                }

                await City.GetCities();
                await City.DefaultCity.GetDeals();
                this.LoadingPanel.Visibility = Visibility.Collapsed;
                this.GrayPanel.Visibility = Visibility.Collapsed;
            }

            var cityContainer = await City.GetCities();
            this.CityName.DataContext = City.DefaultCity;
            await LoadDeals();

            this.DefaultViewModel["Cities"] = cityContainer.Values;

            DealGroup dealGroup = await DealGroup.GetDealGroupInstance();
            List<DealGroup> showGroups = dealGroup.Groups.Values.ToList();
            for (int i = 0; i < showGroups.Count; i++)
            {
                this.DefaultViewModel["ShowGroup" + i] = showGroups[i];
            }
        }

        /// <summary>
        /// Lode all Deals and then bind context data for Gridviews
        /// </summary>
        /// <returns>Task</returns>
        private async Task LoadDeals()
        {
            IEnumerable<Deal> deals = await City.DefaultCity.GetRecommends(8);

            if (deals.Count() >= 8)
            {
                List<Deal> recommandDeals = deals.Take(8).ToList();
                for (int i = 0; i < recommandDeals.Count; i++)
                {
                    this.DefaultViewModel["RecommandDeal" + i] = recommandDeals[i];
                }
            }
        }

        /// <summary>
        /// Navigating to CategoryPage when click head Category Button
        /// </summary>
        /// <param name="sender">Object sender</param>
        /// <param name="e">Routed event argument</param>
        private void CategoryButton_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(CategoryPage));
        }

        /// <summary>
        /// Popuping up change city panel when click Change City buttion in App Bar
        /// </summary>
        /// <param name="sender">Object Sender</param>
        /// <param name="e">Routed event argument</param>
        private void AppBarChangeCity_Click(object sender, RoutedEventArgs e)
        {
            this.PopupPanel.IsOpen = true;
            this.GrayPanel.Opacity = 0.9;
            this.GrayPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
            this.LoadingPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            this.cityGridView.SelectedIndex = System.Convert.ToInt32(City.DefaultCity.CityIndex);
        }

        /// <summary>
        /// Re-Binding context data when chaging city 
        /// </summary>
        /// <param name="sender">Object sender</param>
        /// <param name="e">Item click event argument</param>
        private async void CityItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            City.DefaultCity = ((City)(e.ClickedItem));
            this.CityName.DataContext = City.DefaultCity;
            this.GrayPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
            this.PopupPanel.IsOpen = false;
            this.LoadingPanel.Visibility = Visibility.Visible;
            await LoadDeals();
            this.LoadingPanel.Visibility = Visibility.Collapsed;
            this.GrayPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        }

        /// <summary>
        /// Navigating to ItemDetailsPage when click some deal for preview it
        /// </summary>
        /// <param name="sender">Object sender</param>
        /// <param name="e">Item click event argument</param>
        private void Deals_ItemClick(object sender, ItemClickEventArgs e)
        {
            var selectedId = ((Deal)(((Grid)e.ClickedItem).DataContext)).Gid;
            this.Frame.Navigate(typeof(ItemDetailsPage), selectedId);
        }

        /// <summary>
        /// Navigating to ItemsPage when click some category group
        /// </summary>
        /// <param name="sender">Object sender</param>
        /// <param name="e">Clicked item</param>
        private void ShowCategoryGroup_ItemClick(object sender, ItemClickEventArgs e)
        {
            var categoryTpye = ((DealGroup)(((Grid)e.ClickedItem).DataContext)).Category;
            this.Frame.Navigate(typeof(ItemsPage), categoryTpye);
        }

        /// <summary>
        /// Verify network connection status
        /// </summary>
        private bool VerifyNetworkConnectionStatus()
        {
            string connectionProfileInfo = string.Empty;

            try
            {
                ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

                if (InternetConnectionProfile == null)
                {
                    return false;
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

    }
}
